﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.ComponentModel;

namespace WpfMvvmTest
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{

		BindingList<ProductListTable> ProductList = new BindingList<ProductListTable>();
		ProductDatabaseEntities db = new ProductDatabaseEntities();

		public MainWindow()
		{

			InitializeComponent();

			var productRecords =
				from product in db.ProductListTables
				where product.ID != null
				select product;
			foreach (var product in productRecords)
			{
				ProductList.Add(product);
			}

			ListViewProductDetails.ItemsSource = ProductList;
		}

        void clearData()
        {
            txtID.Text = string.Empty;
            txtName.Text = string.Empty;            
            txtPrice.Text = string.Empty;
        }

		private void ListViewProductDetails_SelectionChanged(object sender, SelectionChangedEventArgs e)
		{

		}

		//private void GridViewColumn_TargetUpdated(object sender, DataTransferEventArgs e)
		//{

		//}

		private void btnCreate_Click(object sender, RoutedEventArgs e)
		{
			ProductListTable newPoduct = new ProductListTable();
			newPoduct.Name = txtName.Text;
			newPoduct.Price = txtPrice.Text;

			ProductList.Add(newPoduct);
			db.AddToProductListTables(newPoduct);
			try
			{
				
				int status = db.SaveChanges();
			}
			catch (Exception ex)
			{

				throw ex;
			}
            clearData();
		}

		private void btnUpdate_Click(object sender, RoutedEventArgs e)
		{
            (ListViewProductDetails.SelectedItem as ProductListTable).Name = txtName.Text;
			(ListViewProductDetails.SelectedItem as ProductListTable).Price = txtPrice.Text;
			int id = (ListViewProductDetails.SelectedItem as ProductListTable).ID;
			ProductListTable dbProduct = db.ProductListTables.FirstOrDefault(pro => pro.ID == id);
			dbProduct.Name = txtName.Text;
			dbProduct.Price = txtPrice.Text;
			db.SaveChanges();
            clearData();
		}

        private void btnDelete_Click(object sender, RoutedEventArgs e)
        {
            int delId = (ListViewProductDetails.SelectedItem as ProductListTable).ID;
            ProductListTable dbDelProduct = db.ProductListTables.FirstOrDefault(pro => pro.ID == delId);
            ProductList.Remove(ListViewProductDetails.SelectedItem as ProductListTable);
            db.DeleteObject(dbDelProduct);
            db.SaveChanges();
            clearData();
        }
	}
}
